package com.croofr.global.exceptions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;

import static com.croofr.global.constants.FileConstants.PROPERTY_FILE_EXT;

/**
 * Basic Croofr exception. All not runtime exceptions in Croofr aplication must
 * extended this exception.
 * <p/>
 * User: bednar<br/>
 * Date: Dec 28, 2009<br/>
 * Time: 2:31:37 PM
 */
public class CroofrException extends Exception
{

    private static final Logger LOG = LoggerFactory.getLogger(CroofrException.class);

    private String errorKey;

    /**
     * Constructor for creating CroofrException with key.
     * Key may be used for get localized message from property files.
     *
     * @param errorKey key to property file
     */
    public CroofrException(String errorKey)
    {
        this.errorKey = errorKey;
    }

    /**
     * Constructor for creating CroofrException with nested exception.
     *
     * @param exception nested exception
     */
    public CroofrException(Exception exception)
    {
        super(exception);
    }

    /**
     * Get localied message from property file by specified errorKey and locale.
     * Locale must be not null.
     *
     * @param locale for specify property file
     * @return localized message
     */
    public String getLocalizedMessage(Locale locale)
    {
        if (locale == null)
        {
            throw new IllegalArgumentException("Locale is null!!!");
        }

        Class<? extends CroofrException> thisClass = this.getClass();

        StringBuffer resource = new StringBuffer();
        resource.append(thisClass.getSimpleName());
        resource.append("_");
        resource.append(locale.toString());
        resource.append(PROPERTY_FILE_EXT);

        InputStream stream = thisClass.getResourceAsStream(resource.toString());

        Properties properties = new Properties();
        try
        {
            properties.load(stream);
        }
        catch (IOException ioe)
        {
            LOG.error("Error in load property file: '{}' as stream.", resource);

            throw new RuntimeException("Error in load property file! " +
                    "For more information see server log.", ioe);
        }

        return properties.getProperty(errorKey, errorKey);
    }

    /**
     * ErrorKey of actual exception.
     *
     * @return errorKey
     */
    public String getErrorKey()
    {
        return errorKey;
    }
}
